<?php

class Rsa
{
    private static $PRIVATE_KEY = '-----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKbVhyEl0dXL2Jew
N9B8wQHaZ07nC5oSKpQR6sc7sdsoqS+G4h9zuFpBXlspOIpnvoWeSRckwX6icytC
uuqThOJaVhmiKV6w8zzyOvTVn0yaHMpXu9ZuhWFhx3xzDYy5rQfAAzKX1MO3k4ta
ZPTQLj8u7vaVEvbVq/FFO+YNCgCpAgMBAAECgYB1x4s1eJiyAc4wEITm2Bv+Lez/
BBfptmd+z0NbUiZW3VbLqcLbh3ufpERzwR8cfu8/L6bUAuvjddYutVZ2Ip0Nd7dG
5rrktH+7R8UT89fn87bUa5NlLee+egyoz/PJ63X4JjEg5OJbkXMbK4YrTypS0IAx
nZv+7BeSsCrzNlpWAQJBANgmHMDNrIWvU3qVf7u8SS/g+WrlvKMWOXtYjH2OqWoO
Vtmh4Or1PbaPIMnPAXFYiYYW8wcLYnVmVCez5qaysWkCQQDFl9XONZIMFAvdJ5S2
UFk63bEYtCroKZjddTlE6K/j+Vj2IaCFm94i4x1YzJR0KrykrtBTLRi7nuWmdJMJ
r61BAkA7dxDGAk+KX9fJi8OedIh2AaDcxeOFwqGBy7Sq/kqhgNxn918XhOy7gtj0
bFzrP/5lw36M25b00XgpjBbSmaqxAkBnBN/TUHjh1T3OQ0m0uDWdjGI+KAlK3A04
QVrng43ZBXMNeMDRiE+Lzu/JEXjBDFsoXYB+LT/86j5/x721yiNBAkEAgi0F5BvA
wYZQXqAx3iyuj8R9uUKpLePafyBRHnLNrFux2VD0ZX3pXCmfDDmtM/NMO491dI84
6NbVOvxWcNPQ/Q==
-----END PRIVATE KEY-----';

    private static $PUBLIC_KEY = '-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCm1YchJdHVy9iXsDfQfMEB2mdO
5wuaEiqUEerHO7HbKKkvhuIfc7haQV5bKTiKZ76FnkkXJMF+onMrQrrqk4TiWlYZ
oilesPM88jr01Z9MmhzKV7vWboVhYcd8cw2Mua0HwAMyl9TDt5OLWmT00C4/Lu72
lRL21avxRTvmDQoAqQIDAQAB
-----END PUBLIC KEY-----';

    private $pubKey;
    private $privateKey;

    public function __construct(){
        $this->pubKey = self::getPublicKey();
        $this->privateKey = self::getPrivateKey();
    }

    /**
	 *返回对应的私钥
	 */
    private static function getPrivateKey(){
        $privateKey = self::$PRIVATE_KEY;
        return openssl_pkey_get_private($privateKey);
    }

    private static function getPublicKey(){
        $pubKey = self::$PUBLIC_KEY;
        return openssl_pkey_get_public($pubKey);
    }

    /**
	 * 公钥加密
	 */
    public function pubEncrypt($decrypted){
        $crypto = '';
        $arr = str_split($decrypted, 117);
        foreach ($arr as $chunk) {
            if (!openssl_public_encrypt($chunk, $encryptData, $this->pubKey))
                return false;
            $crypto .= $encryptData;
        }
        return base64_encode($crypto);
    }

    /**
	 * 私钥解密
	 */
    public function privDecrypt($encrypted){
        $crypto = '';
        $data = base64_decode($encrypted);
        $arr = str_split($data, 128);
        foreach ($arr as $chunk) {
            if (!openssl_private_decrypt($chunk, $decryptData, $this->privateKey))
                return false;
            $crypto .= $decryptData;
        }
        return $crypto;
    }
}